package com.geekaca.d09.work;

import java.io.*;
import java.util.ArrayList;

public class Test2 {
    // 查找项目中的 .java文件,复制到 项目文件夹下的 copydis文件夹
    public static void main(String[] args) {
        ArrayList<File> fileList = new ArrayList<>();
        File path = new File("StudyIO1\\src");
        File distPath = new File("copydis\\");
        distPath.mkdir();


        fileList = searchFile(path, fileList);
//        System.out.println(fileList);

        fileList.forEach(file -> {
            try {
                copyFiles(file, distPath);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        });

    }

    public static void copyFiles(File orgFile, File distDir) throws FileNotFoundException {
        InputStream is = new FileInputStream(orgFile);
        OutputStream os = new FileOutputStream(distDir.getName() + File.separator + orgFile.getName());
//        System.out.println(distDir.getName() + File.separator + orgFile.getName());
        try (is; os) {
            byte[] buffer = new byte[1024];
            int len;
            while ((len = is.read(buffer)) != -1) {
                os.write(buffer, 0, len);
            }
            System.out.println("复制完成.");
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    public static ArrayList<File> searchFile(File dir, ArrayList<File> fileList) {
        if (dir != null && dir.isDirectory()) {
            File[] files = dir.listFiles();

            if (files.length != 0) {
                for (int i = 0; i < files.length; i++) {
                    File curFile = files[i];
                    if (curFile.isFile()) {
                        if (curFile.getName().contains(".java")) {
                            fileList.add(curFile);
                            System.out.println("找到文件:   " + curFile.getName());
                        }
                    } else {
//                        System.out.println(curFile.getAbsolutePath() + " 是文件夹");
                        searchFile(curFile, fileList);
                    }
                }
            }
        }
        return fileList;
    }

}
